package cn.stylefeng.guns.modular.hx.basic.controller;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.http.HttpRequest;
import cn.stylefeng.guns.modular.basic.model.params.BasicXlbOauth2tokenParam;
import cn.stylefeng.guns.modular.basic.model.result.BasicXlbOauth2tokenResult;
import cn.stylefeng.guns.modular.basic.service.BasicWarehouseService;
import cn.stylefeng.guns.modular.basic.service.BasicXlbOauth2tokenService;
import cn.stylefeng.guns.modular.hx.basic.entity.HxBasicPositionGoods;
import cn.stylefeng.guns.modular.hx.basic.model.params.HxBasicGoodsCodeParam;
import cn.stylefeng.guns.modular.hx.basic.service.HxBasicGoodsCodeService;
import cn.stylefeng.guns.modular.hx.storage.model.params.HxStorageStockParam;
import cn.stylefeng.guns.modular.hx.storage.model.result.HxStorageStockResult;
import cn.stylefeng.guns.modular.hx.storage.service.HxStoragePutDetailedService;
import cn.stylefeng.guns.modular.hx.storage.service.HxStorageStockService;
import cn.stylefeng.roses.core.util.ToolUtil;
import lombok.val;
import org.apache.commons.io.IOUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.base.shiro.annotion.Permission;
import cn.stylefeng.guns.modular.basic.entity.BasicCustomer;
import cn.stylefeng.guns.modular.basic.service.BasicCustomerService;
import cn.stylefeng.guns.modular.hx.basic.entity.HxBasicGoods;
import cn.stylefeng.guns.modular.hx.basic.model.params.HxBasicGoodsParam;
import cn.stylefeng.guns.modular.hx.basic.model.result.HxBasicGoodsCodeResult;
import cn.stylefeng.guns.modular.hx.basic.model.result.HxBasicGoodsResult;
import cn.stylefeng.guns.modular.hx.basic.service.HxBasicGoodsService;
import cn.stylefeng.guns.modular.hx.basic.service.HxBasicPositionGoodsService;
import cn.stylefeng.guns.modular.hx.order.model.params.HxOrderOutDetailedParam;
import cn.stylefeng.guns.modular.hx.order.model.result.HxOrderOutDetailedResult;
import cn.stylefeng.guns.modular.hx.order.service.HxOrderOutDetailedService;
import cn.stylefeng.guns.sys.modular.system.entity.User;
import cn.stylefeng.guns.sys.modular.system.service.UserService;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.reqres.response.ResponseData;


/**
 * 商品信息表控制器
 *
 * @author zhucx
 * @Date 2023-06-18 09:12:06
 */
@Controller
@RequestMapping("/hxBasicGoods")
public class HxBasicGoodsController extends BaseController {

    private String PREFIX = "/hx/basic/hxBasicGoods";

    @Autowired
    private HxBasicGoodsService hxBasicGoodsService;

    @Autowired
    private BasicWarehouseService basicWarehouseService;

    @Autowired
    private HxBasicGoodsCodeService hxBasicGoodsCodeService;
    @Autowired
    private BasicCustomerService basicCustomerService;

    @Autowired
    private UserService userService;


    @Autowired
    private HxStoragePutDetailedService hxStoragePutDetailedService;
    @Autowired
    private BasicXlbOauth2tokenService basicXlbOauth2tokenService;
    /**
     * 去打印标签页面
     * zfz
     */
    @RequestMapping("/tobtnqrCode")
    public String tobtnqrCode() {

        return PREFIX + "/btnqrCode.html";
    }
    /**
     * 跳转到主页面
     *
     * @author zhucx
     * @Date 2023-06-18
     */
    @RequestMapping("")
    public String index(Model model) {
    	User user = userService.getcurrentUser();
    	//查询可选择客户
    	model.addAttribute("customerlist", basicCustomerService.findAvailableList(user.getDeptId(),user.getDeliverId(),user.getOperateId()));
        return PREFIX + "/hxBasicGoods.html";
    }

    @RequestMapping("hxBasicGoodsYpdw")
    public String hxBasicGoodsYpdw(Model model) {
        User user = userService.getcurrentUser();
        Long deptId = user.getDeptId();
        Long deliverId = user.getDeliverId();
        //查询可选择仓库
        model.addAttribute("basicWarehouseList", basicWarehouseService.findAvailableList(deptId,deliverId,user.getOperateId()));
        return PREFIX + "/hxBasicGoodsYpdw.html";
    }

    @RequestMapping("hxBasicGoodsGjkcWgx")
    public String hxBasicGoodsGjkcWgx(Model model) {
        User user = userService.getcurrentUser();
        Long deptId = user.getDeptId();
        Long deliverId = user.getDeliverId();
        //查询可选择仓库
        model.addAttribute("basicWarehouseList", basicWarehouseService.findAvailableList(deptId,deliverId,user.getOperateId()));
        return PREFIX + "/hxBasicGoodsGjkcWgx.html";
    }

    @RequestMapping("hxBasicGoodsWH")
    public String hxBasicGoodsWH(Model model) {
        User user = userService.getcurrentUser();
        Long deptId = user.getDeptId();
        Long deliverId = user.getDeliverId();
        //查询可选择仓库
        model.addAttribute("basicWarehouseList", basicWarehouseService.findAvailableList(deptId,deliverId,user.getOperateId()));
        return PREFIX + "/hxBasicGoodswh.html";
    }

    /**
     * 查询商品列表
     */
    @ResponseBody
    @RequestMapping("/ChoiceGoods")
    public LayuiPageInfo ChoiceGoods(HxBasicGoodsParam param, String condition) {
        User user = userService.getcurrentUser();
        param.setDeptId(user.getDeptId());
        param.setDeliverId(user.getDeliverId());
        return this.hxBasicGoodsService.findOneBySpec(param,condition,user.getOperateId());
    }
    // 跳转到拉取商品页面
    @RequestMapping("pickProducts")
    public String pickProducts(Model model) {
        User user = userService.getcurrentUser();
        //查询可选择客户
        model.addAttribute("customerlist", basicCustomerService.findAvailableList(user.getDeptId(),user.getDeliverId(),user.getOperateId()));
        return PREFIX + "/pickProducts.html";
    }
    /**
     * 选择商品页面
     * @author zhucx
     * @Date 2023-06-18
     */
    @RequestMapping("toChoiceGoods")
    public String toChoiceGoods(Model model) {
    	User user = userService.getcurrentUser();
    	//查询可选择客户
    	model.addAttribute("customerlist", basicCustomerService.findAvailableList(user.getDeptId(),user.getDeliverId(),user.getOperateId()));
        return PREFIX + "/choiceGoods.html";
    }

    /**
     * 选择商品页面
     * @author zhucx
     * @Date 2023-06-18
     */
    @RequestMapping("toChoiceGoods_od")
    public String toChoiceGoods_od(Model model) {
    	User user = userService.getcurrentUser();
    	//查询可选择客户
    	model.addAttribute("customerlist", basicCustomerService.findAvailableList(user.getDeptId(),user.getDeliverId(),user.getOperateId()));
        return PREFIX + "/choiceGoodsOd.html";
    }

    /**
     * 导入页面
     */
    @RequestMapping("/toimportExcel")
    public String toimportExcel(Model model) {
    	User user = userService.getcurrentUser();
    	//查询可选择客户
    	model.addAttribute("customerlist", basicCustomerService.findAvailableList(user.getDeptId(),user.getDeliverId(),user.getOperateId()));
        return PREFIX + "/import.html";
    }

    /**
     * 导入页面
     */
    @RequestMapping("/toimportExcelUpdate")
    public String toimportExcelUpdate(Model model) {
    	User user = userService.getcurrentUser();
    	//查询可选择客户
    	model.addAttribute("customerlist", basicCustomerService.findAvailableList(user.getDeptId(),user.getDeliverId(),user.getOperateId()));
        return PREFIX + "/importUpdate.html";
    }

    /**
     * 导入excel   
     */
	@RequestMapping(value = "/importExcel" , method = {RequestMethod.POST} )
    @ResponseBody
    @Permission
    @Transactional(rollbackFor = Exception.class, timeout = 800000)

    public ResponseData importExceNewmethodl(@RequestPart("file") MultipartFile file,  HxBasicGoodsParam hxBasicGoodsParam)  {
		ResponseData data = new ResponseData();
        Object goodsCustomerId = hxBasicGoodsParam.getGoodsCustomerId();
        if (goodsCustomerId != null) {
            BasicCustomer basicCustomer = basicCustomerService.getById(Integer.parseInt(goodsCustomerId.toString()));
            hxBasicGoodsParam.setGoodsCustomerName(basicCustomer.getCustomerName());
        }
        User user = userService.getcurrentUser();
        hxBasicGoodsParam.setDeliverId(user.getDeliverId());
        hxBasicGoodsParam.setDeptId(user.getDeptId());
        hxBasicGoodsParam.setCreateName(user.getName());
        hxBasicGoodsParam.setOperateId(user.getOperateId());
		try {
			data = hxBasicGoodsService.getExceldata(file,hxBasicGoodsParam,data);//处理导入数据
		} catch (Exception e) {
			data.setSuccess(false);
			e.printStackTrace();
		}
        return data;
    }

    /**
     * 导入excel   
     */
	@RequestMapping(value = "/importExcelUpdate" , method = {RequestMethod.POST} )
    @ResponseBody
    @Permission
    public ResponseData importExceNewmethodlUpdate(@RequestPart("file") MultipartFile file,  HxBasicGoodsParam hxBasicGoodsParam)  {
		ResponseData data = new ResponseData();
        User user = userService.getcurrentUser();
        hxBasicGoodsParam.setDeliverId(user.getDeliverId());
        hxBasicGoodsParam.setDeptId(user.getDeptId());
        hxBasicGoodsParam.setOperateId(user.getOperateId());
		try {
			data = hxBasicGoodsService.getExceldataUpdate(file,hxBasicGoodsParam,data);//处理导入数据
		} catch (Exception e) {
			data.setSuccess(false);
			e.printStackTrace();
		}
        return data;
    }
    
    /**
     * 下载模板
     * @throws ServletException , IOException
     */
    @RequestMapping("downloadExcel")
    public void downloadExcel(HttpServletRequest request,HttpServletResponse response) throws ServletException ,IOException {
        String path = "assets/excel/goods_hx.xlsx";
        try {
            InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(path);
            OutputStream  outputStream = response.getOutputStream();
            //设置下载的文件类型
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            //设置下载文件名
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(("零售商品模板" + ".xlsx").getBytes(), "iso-8859-1"));
            IOUtils.copy(inputStream, outputStream);
            outputStream.flush();
            inputStream.close();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 查看详情接口
     *
     * @author zhucx
     * @Date 2023-08-14
     */
    @RequestMapping("/details")
    @ResponseBody
    public ResponseData details(HxBasicGoodsParam hxBasicGoodsParam) {

        HxBasicGoods hxBasicGoods = Optional.ofNullable(this.hxBasicGoodsService.lambdaQuery()
                        .eq(HxBasicGoods::getId, hxBasicGoodsParam.getId())
                        .one())
                .orElseGet(() -> new HxBasicGoods());
        return ResponseData.success(hxBasicGoods);
    }
    /**
     * 新增页面
     *
     * @author zhucx
     * @Date 2023-06-18
     */
    @RequestMapping("/add")
    public String add(Model model) {
    	User user = userService.getcurrentUser();
    	//查询可选择客户
    	model.addAttribute("customerlist", basicCustomerService.findAvailableList(user.getDeptId(),user.getDeliverId(),user.getOperateId()));
        return PREFIX + "/hxBasicGoods_add.html";
    }

    /**
     * 编辑页面
     *
     * @author zhucx
     * @Date 2023-06-18
     */
    @RequestMapping("/edit")
    public String edit(Model model) {
    	User user = userService.getcurrentUser();
    	//查询可选择客户
    	model.addAttribute("customerlist", basicCustomerService.findAvailableList(user.getDeptId(),user.getDeliverId(),user.getOperateId()));
        return PREFIX + "/hxBasicGoods_edit.html";
    }
    /**
     * 跳转到校验
     *
     * @author
     * @Date 2023-04-20
     */
    @RequestMapping("check")
    public String check(Model model) {
        User user = userService.getcurrentUser();
        //查询可选择客户
        model.addAttribute("customerlist", basicCustomerService.findAvailableList(user.getDeptId(),user.getDeliverId(),user.getOperateId()));
        return PREFIX + "/check.html";
    }

    /**
     * 跳转到校验拆零商品
     *
     * @author
     * @Date 2023-04-20
     */
    @RequestMapping("checks")
    public String checks(Model model) {
        User user = userService.getcurrentUser();
        //查询可选择客户
        model.addAttribute("customerlist", basicCustomerService.findAvailableList(user.getDeptId(),user.getDeliverId(),user.getOperateId()));
        return PREFIX + "/checks.html";
    }

    @RequestMapping("/checksgoods")
    @ResponseBody
    public ResponseData checksgoods(Integer customerId) {
        User user = userService.getcurrentUser();
        BasicCustomer r = basicCustomerService.getById(customerId);
        HxBasicGoodsParam param = new HxBasicGoodsParam();
        param.setDeptId(user.getDeptId());
        param.setDeliverId(user.getDeliverId());
        param.setOperateId(user.getOperateId());
        param.setGoodsCustomerId(customerId);
        List<HxBasicGoodsResult> list = hxBasicGoodsService.findListBySpec(param);



        if(ToolUtil.isEmpty(r.getGsnumber())) {
            return ResponseData.error("请维护新零帮公司号");
        }

        //      String url = "https://test-api.xlbsoft.com/api/hxl.open.item.findbyupdatetime";
        String url = "https://hxl-api.xlbsoft.com/api/hxl.open.item.findbyupdatetime";

        // 创建订单数组
        JSONArray ordersArray = new JSONArray();

        // 创建订单对象
        JSONObject orderObject = new JSONObject();
        orderObject.put("direction", "ASC");
        orderObject.put("property", "id");

        // 将订单对象添加到订单数组中
        ordersArray.put(orderObject);

        // 创建请求参数对象
        JSONObject json = new JSONObject();
        json.put("orders", ordersArray);
        json.put("page_number", 1);
        json.put("page_size", 200);
        json.put("update_time", "");


        BasicXlbOauth2tokenParam oauth2tokenParam = new BasicXlbOauth2tokenParam();
        oauth2tokenParam.setDeliverId(r.getDeliverId());
        oauth2tokenParam.setGsnumber(r.getGsnumber());
        BasicXlbOauth2tokenResult oauth2tokenResult = basicXlbOauth2tokenService.findBySpec(oauth2tokenParam);

        String response = HttpRequest.post(url)
                .header("Authorization", "Bearer "+oauth2tokenResult.getOauth2TokenXlb())
                .body(json.toString()).execute().body();
        JSONObject jsonObject = new JSONObject(response);
        List<HxBasicGoods> batchToAdd = new ArrayList<>();

        if (jsonObject.get("code").toString().equals("0")) {
            JSONObject data = jsonObject.getJSONObject("data");
            Object totalElements = ((JSONObject) data).get("total_elements");// 总商品数
            Object totalPages = ((JSONObject) data).get("total_pages");//总页数

            int pageNumber = 0; // 初始页号

            Map<String, HxBasicGoodsCodeResult> goodsCodeMap = new HashMap<>();
            HxBasicGoodsCodeParam goodsCodep = new HxBasicGoodsCodeParam();
            goodsCodep.setDeptId(user.getDeptId());
            goodsCodep.setDeliverId(user.getDeliverId());
            goodsCodep.setOperateId(user.getOperateId());
            List<HxBasicGoodsCodeResult> hxgcp = hxBasicGoodsCodeService.findListBySpec(goodsCodep);
            for (HxBasicGoodsCodeResult pr : hxgcp) {
                if(ToolUtil.isNotEmpty(pr.getXlbCategoryId())) {
                    goodsCodeMap.put(pr.getXlbCategoryId(), pr);
                }
            }
            for (int i = 0; i < (int)totalPages; i++) {

                pageNumber++; // 增加页号，请求下一页数据
                // 创建请求参数对象
                JSONObject jsons = new JSONObject();
                jsons.put("orders", ordersArray);
                jsons.put("page_number", i);
                jsons.put("page_size", 200);
                jsons.put("update_time", "");

                String post = HttpRequest.post(url)
                        .header("Authorization", "Bearer "+oauth2tokenResult.getOauth2TokenXlb())
                        .body(jsons.toString()).execute().body();
                JSONObject object = new JSONObject(post);
                //System.out.println("================jsons："+jsons+"========================");
                //System.out.println("================post："+post+"========================");

                Object data1 = object.opt("data");

                JSONArray content  = ((JSONObject) data1).getJSONArray("content");// 商品明细

                if (content.length() > 0) {
                    for (Object contents: content){
                        HxBasicGoods hxBasicGoodsParam=new HxBasicGoods();
                        Object  basicHeight= ((JSONObject) contents).get("basic_height");// 基本单位高度
                        Object  basicLength= ((JSONObject) contents).get("basic_length");// 基本单位长度
                        Object  basicWidth= ((JSONObject) contents).get("basic_width");// 基本单位宽度
                        Object  categoryId= ((JSONObject) contents).get("category_id");// 商品分类id



                        Object  code= ((JSONObject) contents).get("code");// 商品代码
                        Object  barCode= ((JSONObject) contents).get("bar_code");// 商品条码
                        Object  createTime= ((JSONObject) contents).get("create_time");// 创建时间
                        Object  dateInType= ((JSONObject) contents).get("date_in_type");// 日期录入规则: 0-无日期 1-生产日期 2-到期日期
                        Object  expireType= ((JSONObject) contents).get("expire_type");//保质期类型：1-按天数 2-按月份
                        Object  expireTypeNum= ((JSONObject) contents).get("expire_type_num");// 保质期天数或月数
                        Object  grossWeight= ((JSONObject) contents).get("gross_weight");// 毛重
                        Object  height= ((JSONObject) contents).get("height");// 商品高度
                        Object  id= ((JSONObject) contents).get("id");// 商品id
                        Object  length= ((JSONObject) contents).get("length");//商品长度
                        Object  name= ((JSONObject) contents).get("name");// 商品名称
                        Object  netWeight= ((JSONObject) contents).get("net_weight");// 净重
                        Object  period= ((JSONObject) contents).get("period");// 保质期
                        Object  unit= ((JSONObject) contents).get("unit");//基本单位
                        Object  updateTime1= ((JSONObject) contents).get("update_time");//修后修改时间
                        Object  volume= ((JSONObject) contents).get("volume");// 商品体积
                        Object  weigh= ((JSONObject) contents).get("weigh");// 是否称重
                        Object  width= ((JSONObject) contents).get("width");//商品宽度
                        Object  weightSpec= ((JSONObject) contents).get("purchase_spec");//规格
                        Object purchaseRatio = ((JSONObject) contents).get("purchase_ratio");//采购单位换算率
                        Object purchaseUnit = ((JSONObject) contents).get("purchase_unit");//采购单位
                        Object purchasePrice = ((JSONObject) contents).get("purchase_price");//采购价
                        Object deliveryRatio = ((JSONObject) contents).get("delivery_ratio");//配送单位换算率
                        Object deliveryUnit = ((JSONObject) contents).get("delivery_unit");//配送单位
                        Object deliveryPrice = ((JSONObject) contents).get("delivery_price");//配送价
                        Object wholesaleRatio = ((JSONObject) contents).get("wholesale_ratio");//批发单位换算率
                        Object wholesaleUnit = ((JSONObject) contents).get("wholesale_unit");//批发单位
                        Object wholesalePrice = ((JSONObject) contents).get("wholesale_price");//批发价
                        Object purchaseVolume = ((JSONObject) contents).get("purchase_volume");//采购体积


                        Object stockRatio = ((JSONObject) contents).get("stock_ratio");//库存单位换算率
                        Object stockUnit = ((JSONObject) contents).get("stock_unit");//库存单位
                        Object demolitionState = ((JSONObject) contents).get("demolition_state");//是否拆零

//                    HxBasicGoods goodsid = hxBasicGoodsService.lambdaQuery()
//                            .eq(HxBasicGoods::getGoodsXlbId, String.valueOf(id))
//                            .one();
//                   if (goodsid == null){

                        hxBasicGoodsParam.setGoodsXlbId(String.valueOf(id));
                        hxBasicGoodsParam.setGoodsName(String.valueOf(name));
                        hxBasicGoodsParam.setGoodsPcode69(String.valueOf(barCode));
                        hxBasicGoodsParam.setGoodsNumber(String.valueOf(code));
                        if (ToolUtil.isNotEmpty(weightSpec.toString())&&!weightSpec.toString().equals("null")) {
                            hxBasicGoodsParam.setGoodsSpecs(String.valueOf(weightSpec));
                        }
//                    hxBasicGoodsService.findgoods(hxBasicGoodsParam);


                        hxBasicGoodsParam.setJibenUnit(String.valueOf(unit));
                        hxBasicGoodsParam.setKcUnit(String.valueOf(stockUnit));
                        hxBasicGoodsParam.setKcRate(String.valueOf(stockRatio));
                        hxBasicGoodsParam.setCgUnit(String.valueOf(purchaseUnit));
                        hxBasicGoodsParam.setCgRate(String.valueOf(purchaseRatio));
                        hxBasicGoodsParam.setPfRate(String.valueOf(wholesaleRatio));
                        hxBasicGoodsParam.setPfUnit(String.valueOf(wholesaleUnit));
                        hxBasicGoodsParam.setPsRate(String.valueOf(deliveryRatio));
                        hxBasicGoodsParam.setPsUnit(String.valueOf(deliveryUnit));
                        hxBasicGoodsParam.setCreateTime(new Date());
                        hxBasicGoodsParam.setCreateName(user.getName());
                        hxBasicGoodsParam.setDeliverId(user.getDeliverId());
                        hxBasicGoodsParam.setDeptId(user.getDeptId());
                        hxBasicGoodsParam.setGoodsCustomerName(r.getCustomerName());
                        hxBasicGoodsParam.setGoodsCustomerId(r.getId());
                        hxBasicGoodsParam.setGoodsBottom("10");
                        hxBasicGoodsParam.setGoodsLamination("10");
                        hxBasicGoodsParam.setGoodsTraylayer("1");
                        hxBasicGoodsParam.setGoodsSupportvolume("100");

                        hxBasicGoodsParam.setGoodsChargingCg(String.valueOf(purchasePrice));
                        hxBasicGoodsParam.setGoodsChargingPf(String.valueOf(wholesalePrice));
                        hxBasicGoodsParam.setGoodsChargingPs(String.valueOf(deliveryPrice));
                        hxBasicGoodsParam.setAnquanNum("14");
                        if (ToolUtil.isNotEmpty(expireTypeNum.toString())&&!expireTypeNum.toString().equals("null")) {
                            if (expireType.toString().equals("2")){
                                hxBasicGoodsParam.setGoodsWarranty(String.valueOf(expireTypeNum));
                            }
                            if (expireType.toString().equals("1")){
                                hxBasicGoodsParam.setGoodsWarranty(String.valueOf((int)expireTypeNum/30));
                            }
                        }else{
                            hxBasicGoodsParam.setGoodsWarranty("36");
                        }

                        if (ToolUtil.isNotEmpty(width.toString())&&!width.toString().equals("null")) {
                            hxBasicGoodsParam.setWidth(String.valueOf(width));

                        }else{
                            hxBasicGoodsParam.setWidth("0.1");
                        }
                        if (ToolUtil.isNotEmpty(height.toString())&&!height.toString().equals("null")) {
                            hxBasicGoodsParam.setHeight(String.valueOf(height));
                        }else{
                            hxBasicGoodsParam.setHeight("0.1");
                        }
                        if (ToolUtil.isNotEmpty(length.toString())&&!length.toString().equals("null")) {
                            hxBasicGoodsParam.setLength(String.valueOf(length));
                        }else{
                            hxBasicGoodsParam.setLength("0.1");
                        }
                        if (ToolUtil.isNotEmpty(purchaseVolume.toString())&&!purchaseVolume.toString().equals("null")) {
                            BigDecimal volumeRate = new BigDecimal(purchaseVolume.toString());
                            hxBasicGoodsParam.setGoodsVolume(volumeRate.setScale(4, BigDecimal.ROUND_HALF_UP).toString());
                        }else{
                            hxBasicGoodsParam.setGoodsVolume("0.1");
                        }

                        if (ToolUtil.isNotEmpty(netWeight.toString())&&!netWeight.toString().equals("null")) {
                            hxBasicGoodsParam.setGoodsWeight(String.valueOf(netWeight));

                        }else{
                            hxBasicGoodsParam.setGoodsWeight("0.1");
                        }

                        HxBasicGoodsCodeResult  hxBasicGoodsCode = goodsCodeMap.get(categoryId.toString());
                        if (hxBasicGoodsCode != null) {
                            hxBasicGoodsParam.setGoodsBigtype(hxBasicGoodsCode.getCodeName());
                            hxBasicGoodsParam.setGoodsBigtypedictId((long)hxBasicGoodsCode.getId());

                        }else{
                            hxBasicGoodsParam.setGoodsBigtypedictId(0L);

                        }

                        if (ToolUtil.isNotEmpty(dateInType.toString())&&!dateInType.toString().equals("null")){
                            if (String.valueOf(demolitionState).equals("true")){
                                hxBasicGoodsParam.setDismantlingParts("是");
                            }
                            if (String.valueOf(demolitionState).equals("false")){
                                hxBasicGoodsParam.setDismantlingParts("否");
                            }
                        }else{
                            hxBasicGoodsParam.setDismantlingParts("");
                        }


                        batchToAdd.add(hxBasicGoodsParam);
                    }
                }

            }
        }

        // 创建一个Map<商品编号, HxBasicGoods>，便于通过商品编号查找
        Map<String, HxBasicGoods> batchToAddMap = new HashMap<>();
        for (HxBasicGoods good : batchToAdd) {
            batchToAddMap.put(good.getGoodsNumber(), good);
        }

        List<HxBasicGoods> differentConversionRates = new ArrayList<>();


        // 遍历list，进行换算率比较
        for (HxBasicGoodsResult sourceGood : list) {
            HxBasicGoods targetGood = batchToAddMap.get(sourceGood.getGoodsNumber());
            if (targetGood != null) {
                String sourceDismantlingParts = sourceGood.getDismantlingParts();
                String targetDismantlingParts = targetGood.getDismantlingParts();

                if (!sourceDismantlingParts.equals(targetDismantlingParts)) {
                    differentConversionRates.add(targetGood);
                }
            }

        }
        List<String> inconsistentGoodsNumbers = new ArrayList<>();
        for (HxBasicGoods good : differentConversionRates) {
            //System.out.println("存在拆零状态不一致的商品：" + good.getGoodsNumber());
            inconsistentGoodsNumbers.add(good.getGoodsNumber());
        }
        ResponseData res = new ResponseData();
        res.setSuccess(true);
        res.setMessage(inconsistentGoodsNumbers+"");
        return res;
    }
    @RequestMapping("/checkgoods")
    @ResponseBody
    public ResponseData checkgoods(Integer customerId) {
        User user = userService.getcurrentUser();
        BasicCustomer r = basicCustomerService.getById(customerId);
        HxBasicGoodsParam param = new HxBasicGoodsParam();
        param.setDeptId(user.getDeptId());
        param.setDeliverId(user.getDeliverId());
        param.setOperateId(user.getOperateId());
        param.setGoodsCustomerId(customerId);
        List<HxBasicGoodsResult> list = hxBasicGoodsService.findListBySpec(param);



        if(ToolUtil.isEmpty(r.getGsnumber())) {
            return ResponseData.error("请维护新零帮公司号");
        }

        //      String url = "https://test-api.xlbsoft.com/api/hxl.open.item.findbyupdatetime";
        String url = "https://hxl-api.xlbsoft.com/api/hxl.open.item.findbyupdatetime";

        // 创建订单数组
        JSONArray ordersArray = new JSONArray();

        // 创建订单对象
        JSONObject orderObject = new JSONObject();
        orderObject.put("direction", "ASC");
        orderObject.put("property", "id");

        // 将订单对象添加到订单数组中
        ordersArray.put(orderObject);

        // 创建请求参数对象
        JSONObject json = new JSONObject();
        json.put("orders", ordersArray);
        json.put("page_number", 1);
        json.put("page_size", 200);
        json.put("update_time", "");


        BasicXlbOauth2tokenParam oauth2tokenParam = new BasicXlbOauth2tokenParam();
        oauth2tokenParam.setDeliverId(r.getDeliverId());
        oauth2tokenParam.setGsnumber(r.getGsnumber());
        BasicXlbOauth2tokenResult oauth2tokenResult = basicXlbOauth2tokenService.findBySpec(oauth2tokenParam);

        String response = HttpRequest.post(url)
                .header("Authorization", "Bearer "+oauth2tokenResult.getOauth2TokenXlb())
                .body(json.toString()).execute().body();
        JSONObject jsonObject = new JSONObject(response);
        List<HxBasicGoods> batchToAdd = new ArrayList<>();

        if (jsonObject.get("code").toString().equals("0")) {
            JSONObject data = jsonObject.getJSONObject("data");
            Object totalElements = ((JSONObject) data).get("total_elements");// 总商品数
            Object totalPages = ((JSONObject) data).get("total_pages");//总页数

            int pageNumber = 0; // 初始页号

            Map<String, HxBasicGoodsCodeResult> goodsCodeMap = new HashMap<>();
            HxBasicGoodsCodeParam goodsCodep = new HxBasicGoodsCodeParam();
            goodsCodep.setDeptId(user.getDeptId());
            goodsCodep.setDeliverId(user.getDeliverId());
            goodsCodep.setOperateId(user.getOperateId());
            List<HxBasicGoodsCodeResult> hxgcp = hxBasicGoodsCodeService.findListBySpec(goodsCodep);
            for (HxBasicGoodsCodeResult pr : hxgcp) {
                if(ToolUtil.isNotEmpty(pr.getXlbCategoryId())) {
                    goodsCodeMap.put(pr.getXlbCategoryId(), pr);
                }
            }
            for (int i = 0; i < (int)totalPages; i++) {

                pageNumber++; // 增加页号，请求下一页数据
                // 创建请求参数对象
                JSONObject jsons = new JSONObject();
                jsons.put("orders", ordersArray);
                jsons.put("page_number", i);
                jsons.put("page_size", 200);
                jsons.put("update_time", "");

                String post = HttpRequest.post(url)
                        .header("Authorization", "Bearer "+oauth2tokenResult.getOauth2TokenXlb())
                        .body(jsons.toString()).execute().body();
                JSONObject object = new JSONObject(post);
                //System.out.println("================jsons："+jsons+"========================");
                //System.out.println("================post："+post+"========================");

                Object data1 = object.opt("data");

                JSONArray content  = ((JSONObject) data1).getJSONArray("content");// 商品明细

                if (content.length() > 0) {
                    for (Object contents: content){
                        HxBasicGoods hxBasicGoodsParam=new HxBasicGoods();
                        Object  basicHeight= ((JSONObject) contents).get("basic_height");// 基本单位高度
                        Object  basicLength= ((JSONObject) contents).get("basic_length");// 基本单位长度
                        Object  basicWidth= ((JSONObject) contents).get("basic_width");// 基本单位宽度
                        Object  categoryId= ((JSONObject) contents).get("category_id");// 商品分类id



                        Object  code= ((JSONObject) contents).get("code");// 商品代码
                        Object  barCode= ((JSONObject) contents).get("bar_code");// 商品条码
                        Object  createTime= ((JSONObject) contents).get("create_time");// 创建时间
                        Object  dateInType= ((JSONObject) contents).get("date_in_type");// 日期录入规则: 0-无日期 1-生产日期 2-到期日期
                        Object  expireType= ((JSONObject) contents).get("expire_type");//保质期类型：1-按天数 2-按月份
                        Object  expireTypeNum= ((JSONObject) contents).get("expire_type_num");// 保质期天数或月数
                        Object  grossWeight= ((JSONObject) contents).get("gross_weight");// 毛重
                        Object  height= ((JSONObject) contents).get("height");// 商品高度
                        Object  id= ((JSONObject) contents).get("id");// 商品id
                        Object  length= ((JSONObject) contents).get("length");//商品长度
                        Object  name= ((JSONObject) contents).get("name");// 商品名称
                        Object  netWeight= ((JSONObject) contents).get("net_weight");// 净重
                        Object  period= ((JSONObject) contents).get("period");// 保质期
                        Object  unit= ((JSONObject) contents).get("unit");//基本单位
                        Object  updateTime1= ((JSONObject) contents).get("update_time");//修后修改时间
                        Object  volume= ((JSONObject) contents).get("volume");// 商品体积
                        Object  weigh= ((JSONObject) contents).get("weigh");// 是否称重
                        Object  width= ((JSONObject) contents).get("width");//商品宽度
                        Object  weightSpec= ((JSONObject) contents).get("purchase_spec");//规格
                        Object purchaseRatio = ((JSONObject) contents).get("purchase_ratio");//采购单位换算率
                        Object purchaseUnit = ((JSONObject) contents).get("purchase_unit");//采购单位
                        Object purchasePrice = ((JSONObject) contents).get("purchase_price");//采购价
                        Object deliveryRatio = ((JSONObject) contents).get("delivery_ratio");//配送单位换算率
                        Object deliveryUnit = ((JSONObject) contents).get("delivery_unit");//配送单位
                        Object deliveryPrice = ((JSONObject) contents).get("delivery_price");//配送价
                        Object wholesaleRatio = ((JSONObject) contents).get("wholesale_ratio");//批发单位换算率
                        Object wholesaleUnit = ((JSONObject) contents).get("wholesale_unit");//批发单位
                        Object wholesalePrice = ((JSONObject) contents).get("wholesale_price");//批发价
                        Object purchaseVolume = ((JSONObject) contents).get("purchase_volume");//采购体积


                        Object stockRatio = ((JSONObject) contents).get("stock_ratio");//库存单位换算率
                        Object stockUnit = ((JSONObject) contents).get("stock_unit");//库存单位
                        Object demolitionState = ((JSONObject) contents).get("demolition_state");//是否拆零

//                    HxBasicGoods goodsid = hxBasicGoodsService.lambdaQuery()
//                            .eq(HxBasicGoods::getGoodsXlbId, String.valueOf(id))
//                            .one();
//                   if (goodsid == null){

                        hxBasicGoodsParam.setGoodsXlbId(String.valueOf(id));
                        hxBasicGoodsParam.setGoodsName(String.valueOf(name));
                        hxBasicGoodsParam.setGoodsPcode69(String.valueOf(barCode));
                        hxBasicGoodsParam.setGoodsNumber(String.valueOf(code));
                        if (ToolUtil.isNotEmpty(weightSpec.toString())&&!weightSpec.toString().equals("null")) {
                            hxBasicGoodsParam.setGoodsSpecs(String.valueOf(weightSpec));
                        }
//                    hxBasicGoodsService.findgoods(hxBasicGoodsParam);


                        hxBasicGoodsParam.setJibenUnit(String.valueOf(unit));
                        hxBasicGoodsParam.setKcUnit(String.valueOf(stockUnit));
                        hxBasicGoodsParam.setKcRate(String.valueOf(stockRatio));
                        hxBasicGoodsParam.setCgUnit(String.valueOf(purchaseUnit));
                        hxBasicGoodsParam.setCgRate(String.valueOf(purchaseRatio));
                        hxBasicGoodsParam.setPfRate(String.valueOf(wholesaleRatio));
                        hxBasicGoodsParam.setPfUnit(String.valueOf(wholesaleUnit));
                        hxBasicGoodsParam.setPsRate(String.valueOf(deliveryRatio));
                        hxBasicGoodsParam.setPsUnit(String.valueOf(deliveryUnit));
                        hxBasicGoodsParam.setCreateTime(new Date());
                        hxBasicGoodsParam.setCreateName(user.getName());
                        hxBasicGoodsParam.setDeliverId(user.getDeliverId());
                        hxBasicGoodsParam.setDeptId(user.getDeptId());
                        hxBasicGoodsParam.setGoodsCustomerName(r.getCustomerName());
                        hxBasicGoodsParam.setGoodsCustomerId(r.getId());
                        hxBasicGoodsParam.setGoodsBottom("10");
                        hxBasicGoodsParam.setGoodsLamination("10");
                        hxBasicGoodsParam.setGoodsTraylayer("1");
                        hxBasicGoodsParam.setGoodsSupportvolume("100");

                        hxBasicGoodsParam.setGoodsChargingCg(String.valueOf(purchasePrice));
                        hxBasicGoodsParam.setGoodsChargingPf(String.valueOf(wholesalePrice));
                        hxBasicGoodsParam.setGoodsChargingPs(String.valueOf(deliveryPrice));
                        hxBasicGoodsParam.setAnquanNum("14");
                        if (ToolUtil.isNotEmpty(expireTypeNum.toString())&&!expireTypeNum.toString().equals("null")) {
                            if (expireType.toString().equals("2")){
                                hxBasicGoodsParam.setGoodsWarranty(String.valueOf(expireTypeNum));
                            }
                            if (expireType.toString().equals("1")){
                                hxBasicGoodsParam.setGoodsWarranty(String.valueOf((int)expireTypeNum/30));
                            }
                        }else{
                            hxBasicGoodsParam.setGoodsWarranty("36");
                        }

                        if (ToolUtil.isNotEmpty(width.toString())&&!width.toString().equals("null")) {
                            hxBasicGoodsParam.setWidth(String.valueOf(width));

                        }else{
                            hxBasicGoodsParam.setWidth("0.1");
                        }
                        if (ToolUtil.isNotEmpty(height.toString())&&!height.toString().equals("null")) {
                            hxBasicGoodsParam.setHeight(String.valueOf(height));
                        }else{
                            hxBasicGoodsParam.setHeight("0.1");
                        }
                        if (ToolUtil.isNotEmpty(length.toString())&&!length.toString().equals("null")) {
                            hxBasicGoodsParam.setLength(String.valueOf(length));
                        }else{
                            hxBasicGoodsParam.setLength("0.1");
                        }
                        if (ToolUtil.isNotEmpty(purchaseVolume.toString())&&!purchaseVolume.toString().equals("null")) {
                            BigDecimal volumeRate = new BigDecimal(purchaseVolume.toString());
                            hxBasicGoodsParam.setGoodsVolume(volumeRate.setScale(4, BigDecimal.ROUND_HALF_UP).toString());
                        }else{
                            hxBasicGoodsParam.setGoodsVolume("0.1");
                        }

                        if (ToolUtil.isNotEmpty(netWeight.toString())&&!netWeight.toString().equals("null")) {
                            hxBasicGoodsParam.setGoodsWeight(String.valueOf(netWeight));

                        }else{
                            hxBasicGoodsParam.setGoodsWeight("0.1");
                        }

                        HxBasicGoodsCodeResult  hxBasicGoodsCode = goodsCodeMap.get(categoryId.toString());
                        if (hxBasicGoodsCode != null) {
                            hxBasicGoodsParam.setGoodsBigtype(hxBasicGoodsCode.getCodeName());
                            hxBasicGoodsParam.setGoodsBigtypedictId((long)hxBasicGoodsCode.getId());

                        }else{
                            hxBasicGoodsParam.setGoodsBigtypedictId(0L);

                        }

                        if (ToolUtil.isNotEmpty(dateInType.toString())&&!dateInType.toString().equals("null")){
                            if (String.valueOf(demolitionState).equals("true")){
                                hxBasicGoodsParam.setDismantlingParts("是");
                            }
                            if (String.valueOf(demolitionState).equals("false")){
                                hxBasicGoodsParam.setDismantlingParts("否");
                            }
                        }else{
                            hxBasicGoodsParam.setDismantlingParts("");
                        }


                        batchToAdd.add(hxBasicGoodsParam);
                    }
                }

            }
        }

        // 创建一个Map<商品编号, HxBasicGoods>，便于通过商品编号查找
        Map<String, HxBasicGoods> batchToAddMap = new HashMap<>();
        for (HxBasicGoods good : batchToAdd) {
            batchToAddMap.put(good.getGoodsNumber(), good);
        }

        List<HxBasicGoods> differentConversionRates = new ArrayList<>();


        // 遍历list，进行换算率比较
        for (HxBasicGoodsResult sourceGood : list) {
            HxBasicGoods targetGood = batchToAddMap.get(sourceGood.getGoodsNumber());
                if (targetGood != null) {
                    // 比较每种换算率
                    BigDecimal sourceKcRate = new BigDecimal(sourceGood.getKcRate());
                    BigDecimal targetKcRate = new BigDecimal(targetGood.getKcRate());

                    BigDecimal sourceCgRate = new BigDecimal(sourceGood.getCgRate());
                    BigDecimal targetCgRate = new BigDecimal(targetGood.getCgRate());

                    BigDecimal sourcePfRate = new BigDecimal(sourceGood.getPfRate());
                    BigDecimal targetPfRate = new BigDecimal(targetGood.getPfRate());

                    BigDecimal sourcePsRate = new BigDecimal(sourceGood.getPsRate());
                    BigDecimal targetPsRate = new BigDecimal(targetGood.getPsRate());

                    boolean isEqual = sourceKcRate.compareTo(targetKcRate) == 0 &&
                            sourceCgRate.compareTo(targetCgRate) == 0 &&
                            sourcePfRate.compareTo(targetPfRate) == 0 &&
                            sourcePsRate.compareTo(targetPsRate) == 0;

                if (!isEqual) {
                    differentConversionRates.add(targetGood);
                }
            }

        }
        List<String> inconsistentGoodsNumbers = new ArrayList<>();
        for (HxBasicGoods good : differentConversionRates) {
            //System.out.println("存在换算率不一致的商品：" + good.getGoodsNumber());
            //System.out.println("kcRate: " + good.getKcRate());
            //System.out.println("cgRate: " + good.getCgRate());
            //System.out.println("pfRate: " + good.getPfRate());
            //System.out.println("psRate: " + good.getPsRate());
            inconsistentGoodsNumbers.add(good.getGoodsNumber());
        }
        Map<String, Object> responseData = new HashMap<>();
        responseData.put("message", "共有" + differentConversionRates.size() + "个商品存在换算率不一致");
        responseData.put("inconsistentGoodsNumbers", inconsistentGoodsNumbers);
        ResponseData res = new ResponseData();
        res.setSuccess(true);
        res.setMessage(inconsistentGoodsNumbers+"");
        return res;
    }
        /**
         * 拉取新零帮商品信息
         *
         * @author
         * @Date 2023-04-20
         */
    @RequestMapping("/products")
    @ResponseBody
    @Permission
    public ResponseData products(@RequestParam("updateTime") String updateTime ,Integer customerId) {
        User user = userService.getcurrentUser();
        BasicCustomer r = basicCustomerService.getById(customerId);
        if(ToolUtil.isEmpty(r.getGsnumber())) {
            return ResponseData.error("请维护新零帮公司号");
        }

        //      String url = "https://test-api.xlbsoft.com/api/hxl.open.item.findbyupdatetime";
      String url = "https://hxl-api.xlbsoft.com/api/hxl.open.item.findbyupdatetime";

        // 创建订单数组
        JSONArray ordersArray = new JSONArray();

        // 创建订单对象
        JSONObject orderObject = new JSONObject();
        orderObject.put("direction", "ASC");
        orderObject.put("property", "id");

        // 将订单对象添加到订单数组中
        ordersArray.put(orderObject);

        // 创建请求参数对象
        JSONObject json = new JSONObject();
        json.put("orders", ordersArray);
        json.put("page_number", 1);
        json.put("page_size", 200);
        json.put("update_time", "");


        BasicXlbOauth2tokenParam oauth2tokenParam = new BasicXlbOauth2tokenParam();
        oauth2tokenParam.setDeliverId(r.getDeliverId());
        oauth2tokenParam.setGsnumber(r.getGsnumber());
        BasicXlbOauth2tokenResult oauth2tokenResult = basicXlbOauth2tokenService.findBySpec(oauth2tokenParam);

        String response = HttpRequest.post(url)
                .header("Authorization", "Bearer "+oauth2tokenResult.getOauth2TokenXlb())
                .body(json.toString()).execute().body();
        JSONObject jsonObject = new JSONObject(response);

        if (jsonObject.get("code").toString().equals("0")) {
        JSONObject data = jsonObject.getJSONObject("data");
        Object totalElements = ((JSONObject) data).get("total_elements");// 总商品数
        Object totalPages = ((JSONObject) data).get("total_pages");//总页数

        int pageNumber = 0; // 初始页号

		Map<String, HxBasicGoodsCodeResult> goodsCodeMap = new HashMap<>();
		HxBasicGoodsCodeParam goodsCodep = new HxBasicGoodsCodeParam();
		goodsCodep.setDeptId(user.getDeptId());
		goodsCodep.setDeliverId(user.getDeliverId());
		goodsCodep.setOperateId(user.getOperateId());
		List<HxBasicGoodsCodeResult> hxgcp = hxBasicGoodsCodeService.findListBySpec(goodsCodep);
		for (HxBasicGoodsCodeResult pr : hxgcp) {
			if(ToolUtil.isNotEmpty(pr.getXlbCategoryId())) {
				goodsCodeMap.put(pr.getXlbCategoryId(), pr);
			}
		}
        for (int i = 0; i < (int)totalPages; i++) {

            List<HxBasicGoods> batchToAdd = new ArrayList<>(); // 用于存储每一页的数据，批量添加到系统中
            pageNumber++; // 增加页号，请求下一页数据
            // 创建请求参数对象
            JSONObject jsons = new JSONObject();
            jsons.put("orders", ordersArray);
            jsons.put("page_number", i);
            jsons.put("page_size", 200);
            jsons.put("update_time", "");

            String post = HttpRequest.post(url)
                    .header("Authorization", "Bearer " + oauth2tokenResult.getOauth2TokenXlb())
                    .body(jsons.toString()).execute().body();
            JSONObject object = new JSONObject(post);
            //System.out.println("================jsons："+jsons+"========================");
            //System.out.println("================post："+post+"========================");

            Object data1 = object.opt("data");
            if (data1 instanceof JSONObject) {
                JSONArray content = ((JSONObject) data1).getJSONArray("content");// 商品明细

            if (content.length() > 0) {
                for (Object contents : content) {
                    HxBasicGoods hxBasicGoodsParam = new HxBasicGoods();
                    Object basicHeight = ((JSONObject) contents).get("basic_height");// 基本单位高度
                    Object basicLength = ((JSONObject) contents).get("basic_length");// 基本单位长度
                    Object basicWidth = ((JSONObject) contents).get("basic_width");// 基本单位宽度
                    Object categoryId = ((JSONObject) contents).get("category_id");// 商品分类id


                    Object code = ((JSONObject) contents).get("code");// 商品代码
                    Object barCode = ((JSONObject) contents).get("bar_code");// 商品条码
                    Object createTime = ((JSONObject) contents).get("create_time");// 创建时间
                    Object dateInType = ((JSONObject) contents).get("date_in_type");// 日期录入规则: 0-无日期 1-生产日期 2-到期日期
                    Object expireType = ((JSONObject) contents).get("expire_type");//保质期类型：1-按天数 2-按月份
                    Object expireTypeNum = ((JSONObject) contents).get("expire_type_num");// 保质期天数或月数
                    Object grossWeight = ((JSONObject) contents).get("gross_weight");// 毛重
                    Object height = ((JSONObject) contents).get("height");// 商品高度
                    Object id = ((JSONObject) contents).get("id");// 商品id
                    Object length = ((JSONObject) contents).get("length");//商品长度
                    Object name = ((JSONObject) contents).get("name");// 商品名称
                    Object netWeight = ((JSONObject) contents).get("net_weight");// 净重
                    Object period = ((JSONObject) contents).get("period");// 保质期
                    Object unit = ((JSONObject) contents).get("unit");//基本单位
                    Object updateTime1 = ((JSONObject) contents).get("update_time");//修后修改时间
                    Object volume = ((JSONObject) contents).get("volume");// 商品体积
                    Object weigh = ((JSONObject) contents).get("weigh");// 是否称重
                    Object width = ((JSONObject) contents).get("width");//商品宽度
                    Object weightSpec = ((JSONObject) contents).get("purchase_spec");//规格
                    Object purchaseRatio = ((JSONObject) contents).get("purchase_ratio");//采购单位换算率
                    Object purchaseUnit = ((JSONObject) contents).get("purchase_unit");//采购单位
                    Object purchasePrice = ((JSONObject) contents).get("purchase_price");//采购价
                    Object deliveryRatio = ((JSONObject) contents).get("delivery_ratio");//配送单位换算率
                    Object deliveryUnit = ((JSONObject) contents).get("delivery_unit");//配送单位
                    Object deliveryPrice = ((JSONObject) contents).get("delivery_price");//配送价
                    Object wholesaleRatio = ((JSONObject) contents).get("wholesale_ratio");//批发单位换算率
                    Object wholesaleUnit = ((JSONObject) contents).get("wholesale_unit");//批发单位
                    Object wholesalePrice = ((JSONObject) contents).get("wholesale_price");//批发价
                    Object purchaseVolume = ((JSONObject) contents).get("purchase_volume");//采购体积


                    Object stockRatio = ((JSONObject) contents).get("stock_ratio");//库存单位换算率
                    Object stockUnit = ((JSONObject) contents).get("stock_unit");//库存单位
                    Object demolitionState = ((JSONObject) contents).get("demolition_state");//是否拆零

//                    HxBasicGoods goodsid = hxBasicGoodsService.lambdaQuery()
//                            .eq(HxBasicGoods::getGoodsXlbId, String.valueOf(id))
//                            .one();
//                   if (goodsid == null){

                    hxBasicGoodsParam.setGoodsXlbId(String.valueOf(id));
                    hxBasicGoodsParam.setGoodsName(String.valueOf(name));
                    hxBasicGoodsParam.setGoodsPcode69(String.valueOf(barCode));
                    hxBasicGoodsParam.setGoodsNumber(String.valueOf(code));
                    if (ToolUtil.isNotEmpty(weightSpec.toString()) && !weightSpec.toString().equals("null")) {
                        hxBasicGoodsParam.setGoodsSpecs(String.valueOf(weightSpec));
                    }
//                    hxBasicGoodsService.findgoods(hxBasicGoodsParam);


                    hxBasicGoodsParam.setJibenUnit(String.valueOf(unit));
                    hxBasicGoodsParam.setKcUnit(String.valueOf(stockUnit));
                    hxBasicGoodsParam.setKcRate(String.valueOf(stockRatio));
                    hxBasicGoodsParam.setCgUnit(String.valueOf(purchaseUnit));
                    hxBasicGoodsParam.setCgRate(String.valueOf(purchaseRatio));
                    hxBasicGoodsParam.setPfRate(String.valueOf(wholesaleRatio));
                    hxBasicGoodsParam.setPfUnit(String.valueOf(wholesaleUnit));
                    hxBasicGoodsParam.setPsRate(String.valueOf(deliveryRatio));
                    hxBasicGoodsParam.setPsUnit(String.valueOf(deliveryUnit));
                    hxBasicGoodsParam.setCreateTime(new Date());
                    hxBasicGoodsParam.setCreateName(user.getName());
                    hxBasicGoodsParam.setDeliverId(user.getDeliverId());
                    hxBasicGoodsParam.setDeptId(user.getDeptId());
                    hxBasicGoodsParam.setGoodsCustomerName(r.getCustomerName());
                    hxBasicGoodsParam.setGoodsCustomerId(r.getId());
                    hxBasicGoodsParam.setGoodsBottom("10");
                    hxBasicGoodsParam.setGoodsLamination("10");
                    hxBasicGoodsParam.setGoodsTraylayer("1");
                    hxBasicGoodsParam.setGoodsSupportvolume("100");

                    hxBasicGoodsParam.setGoodsChargingCg(String.valueOf(purchasePrice));
                    hxBasicGoodsParam.setGoodsChargingPf(String.valueOf(wholesalePrice));
                    hxBasicGoodsParam.setGoodsChargingPs(String.valueOf(deliveryPrice));
                    hxBasicGoodsParam.setAnquanNum("14");
                    if (ToolUtil.isNotEmpty(expireTypeNum.toString()) && !expireTypeNum.toString().equals("null")) {
                        if (expireType.toString().equals("2")) {
                            hxBasicGoodsParam.setGoodsWarranty(String.valueOf(expireTypeNum));
                        }
                        if (expireType.toString().equals("1")) {
                            hxBasicGoodsParam.setGoodsWarranty(String.valueOf((int) expireTypeNum / 30));
                        }
                    } else {
                        hxBasicGoodsParam.setGoodsWarranty("36");
                    }

                    if (ToolUtil.isNotEmpty(width.toString()) && !width.toString().equals("null")) {
                        hxBasicGoodsParam.setWidth(String.valueOf(width));

                    } else {
                        hxBasicGoodsParam.setWidth("0.1");
                    }
                    if (ToolUtil.isNotEmpty(height.toString()) && !height.toString().equals("null")) {
                        hxBasicGoodsParam.setHeight(String.valueOf(height));
                    } else {
                        hxBasicGoodsParam.setHeight("0.1");
                    }
                    if (ToolUtil.isNotEmpty(length.toString()) && !length.toString().equals("null")) {
                        hxBasicGoodsParam.setLength(String.valueOf(length));
                    } else {
                        hxBasicGoodsParam.setLength("0.1");
                    }
                    if (ToolUtil.isNotEmpty(purchaseVolume.toString()) && !purchaseVolume.toString().equals("null")) {
                        BigDecimal volumeRate = new BigDecimal(purchaseVolume.toString());
                        hxBasicGoodsParam.setGoodsVolume(volumeRate.setScale(4, BigDecimal.ROUND_HALF_UP).toString());
                    } else {
                        hxBasicGoodsParam.setGoodsVolume("0.1");
                    }

                    if (ToolUtil.isNotEmpty(netWeight.toString()) && !netWeight.toString().equals("null")) {
                        hxBasicGoodsParam.setGoodsWeight(String.valueOf(netWeight));

                    } else {
                        hxBasicGoodsParam.setGoodsWeight("0.1");
                    }

                    HxBasicGoodsCodeResult hxBasicGoodsCode = goodsCodeMap.get(categoryId.toString());
                    if (hxBasicGoodsCode != null) {
                        hxBasicGoodsParam.setGoodsBigtype(hxBasicGoodsCode.getCodeName());
                        hxBasicGoodsParam.setGoodsBigtypedictId((long) hxBasicGoodsCode.getId());

                    } else {
                        hxBasicGoodsParam.setGoodsBigtypedictId(0L);

                    }

                    if (ToolUtil.isNotEmpty(dateInType.toString()) && !dateInType.toString().equals("null")) {
                        if (String.valueOf(demolitionState).equals("true")) {
                            hxBasicGoodsParam.setDismantlingParts("是");
                        }
                        if (String.valueOf(demolitionState).equals("false")) {
                            hxBasicGoodsParam.setDismantlingParts("否");
                        }
                    } else {
                        hxBasicGoodsParam.setDismantlingParts("");
                    }


                    batchToAdd.add(hxBasicGoodsParam);
//                    }
                }
            }
        }
            // 批量添加到表中
            if (!batchToAdd.isEmpty()) {
                hxBasicGoodsService.saveBatch(batchToAdd);
            }

         }
        }

        return ResponseData.success();
    }

    /**
     *
     * @param updateTime
     * @param customerId
     * @return
     */

    @RequestMapping("/getTcslProducts")
    @ResponseBody
//    @Permission
    public ResponseData getTcslProducts(@RequestParam("updateTime") String updateTime ,Integer customerId,Integer warehouseId) {
        User user = userService.getcurrentUser();
        BasicCustomer r = basicCustomerService.getById(customerId);

        //获取品项类别档案
        String itemUrl = "https://tcsl.engine.fxscm.net/business/standard/api/v1/item";
        //获取品项单位接口
        String itemUnitUrl= "https://tcsl.engine.fxscm.net/business/standard/api/v1/item_unit";

        // 创建订单对象
        JSONObject orderObject = new JSONObject();
        orderObject.put("entCode", "ENT136140");

        String itemResponse = HttpRequest.post(itemUrl)
                .body(orderObject.toString()).execute().body();

        String itemUnitResponse = HttpRequest.post(itemUnitUrl)
                .body(orderObject.toString()).execute().body();

        JSONObject itemUnitResponseJsonObject = new JSONObject(itemUnitResponse);
        JSONArray itemUnitDatas = new JSONArray();
        if (itemUnitResponseJsonObject.get("code").toString().equals("0")) {
            itemUnitDatas = itemUnitResponseJsonObject.getJSONArray("data");
        }

        JSONObject jsonObject = new JSONObject(itemResponse);
        List<HxBasicGoodsParam> list = new ArrayList<>();
        if (jsonObject.get("code").toString().equals("0")) {
            JSONArray datas = jsonObject.getJSONArray("data");
            JSONArray finalItemUnitDatas = itemUnitDatas;
            for (Object data : datas) {
                AtomicReference<String> jibenUnit = new AtomicReference<>("");
                AtomicReference<String> cgUnit = new AtomicReference<>("");
                AtomicReference<String> kcUnit = new AtomicReference<>("");
                AtomicReference<String> psUnit = new AtomicReference<>("");
                AtomicReference<String> pfUnit = new AtomicReference<>("");

                AtomicReference<String> kcRate = new AtomicReference<>("");
                AtomicReference<String> cgRate = new AtomicReference<>("");
                AtomicReference<String> pfRate = new AtomicReference<>("");
                AtomicReference<String> psRate = new AtomicReference<>("");


                JSONObject data1 = (JSONObject)data;
                Object id = data1.get("id");
                HxBasicGoodsParam hxBasicGoodsParam1 = new HxBasicGoodsParam();
                hxBasicGoodsParam1.setGoodsXlbId(String.valueOf(id));
                List<HxBasicGoodsResult> listBySpec = hxBasicGoodsService.findListBySpec(hxBasicGoodsParam1);
                if (listBySpec.size() > 0) {
                    continue;
                }
                finalItemUnitDatas.forEach(itemUnitData -> {
                    JSONObject itemUnitData1 = (JSONObject)itemUnitData;
                    itemUnitData1 = (JSONObject)itemUnitData;
                    if ("1".equals(itemUnitData1.get("enableFlag").toString())
                            && data1.getString("id").equals(itemUnitData1.getString("itemId"))) {
                        if("1".equals(itemUnitData1.get("mainFlag").toString())){
                            jibenUnit.set(itemUnitData1.getString("name"));
                            pfUnit.set(itemUnitData1.getString("name"));
                            pfRate.set(itemUnitData1.get("ratio").toString());
                            cgUnit.set(itemUnitData1.getString("name"));
                            cgRate.set(itemUnitData1.get("ratio").toString());
                            kcUnit.set(itemUnitData1.getString("name"));
                            kcRate.set(itemUnitData1.get("ratio").toString());
                            psUnit.set(itemUnitData1.getString("name"));
                            psRate.set(itemUnitData1.get("ratio").toString());
                        }
                    }
                });

                finalItemUnitDatas.forEach(itemUnitData -> {
                    JSONObject itemUnitData1 = (JSONObject)itemUnitData;
                    itemUnitData1 = (JSONObject)itemUnitData;
                    if ("1".equals(itemUnitData1.get("enableFlag").toString())
                            && data1.getString("id").equals(itemUnitData1.getString("itemId"))) {
                         if("0".equals(itemUnitData1.get("mainFlag").toString())){
                            if("1".equals(itemUnitData1.get("purchaseFlag").toString())){
                                cgUnit.set(itemUnitData1.getString("name"));
                                cgRate.set(itemUnitData1.get("ratio").toString());
                            }
                            if("1".equals(itemUnitData1.get("checkFirstFlag").toString())){
                                kcUnit.set(itemUnitData1.getString("name"));
                                kcRate.set(itemUnitData1.get("ratio").toString());
                            }
                            if("1".equals(itemUnitData1.get("salesFlag").toString())){
                                psUnit.set(itemUnitData1.getString("name"));
                                psRate.set(itemUnitData1.get("ratio").toString());
                            }
                        }
                    }
                });
                HxBasicGoodsParam hxBasicGoodsParam = new HxBasicGoodsParam();
                hxBasicGoodsParam.setGoodsName(String.valueOf((data1.get("name"))));
                hxBasicGoodsParam.setGoodsNumber(String.valueOf(( data1.get("code"))));
//                hxBasicGoodsParam.setGoodsPcode69(String.valueOf(((JSONObject) data1).get("itemBarCode")));
//                hxBasicGoodsParam.setGoodsSpecs(String.valueOf(((JSONObject) data1).get("itemWeight")));
                hxBasicGoodsParam.setJibenUnit(jibenUnit.get());//基本单位
                hxBasicGoodsParam.setKcUnit(kcUnit.get());//库存单位
                hxBasicGoodsParam.setKcRate(kcRate.get());//库存换算率
                hxBasicGoodsParam.setCgUnit(cgUnit.get());//采购单位
                hxBasicGoodsParam.setCgRate(cgRate.get());//采购换算率
                hxBasicGoodsParam.setPfRate(pfRate.get());//批发换算率
                hxBasicGoodsParam.setPfUnit(pfUnit.get());//批发单位
                hxBasicGoodsParam.setPsRate(psRate.get());//配送换算率
                hxBasicGoodsParam.setPsUnit(psUnit.get());//配送单位
                hxBasicGoodsParam.setCreateTime(new Date());
                hxBasicGoodsParam.setCreateName(user.getName());
                hxBasicGoodsParam.setDeliverId(user.getDeliverId());
                hxBasicGoodsParam.setDeptId(user.getDeptId());
                hxBasicGoodsParam.setGoodsCustomerName(r.getCustomerName());
                hxBasicGoodsParam.setGoodsCustomerId(r.getId());
                hxBasicGoodsParam.setGoodsBottom("10");
                hxBasicGoodsParam.setGoodsLamination("10");
                hxBasicGoodsParam.setGoodsTraylayer("1");
                hxBasicGoodsParam.setGoodsSupportvolume("100");
                hxBasicGoodsParam.setGoodsChargingCg("0");
                hxBasicGoodsParam.setGoodsChargingPf("0");
                hxBasicGoodsParam.setGoodsChargingPs("0");
                hxBasicGoodsParam.setAnquanNum("14");
                Double shelfLife = Double.parseDouble(data1.get("shelfLife").toString());
                double v = shelfLife / 30;
                hxBasicGoodsParam.setGoodsWarranty(String.format("%.2f", v));
                hxBasicGoodsParam.setWidth("0");
                hxBasicGoodsParam.setHeight("0");
                hxBasicGoodsParam.setLength("0");
                hxBasicGoodsParam.setGoodsVolume("0");
                hxBasicGoodsParam.setGoodsWeight("0");
                hxBasicGoodsParam.setDismantlingParts("否");
//                hxBasicGoodsParam.setGoodsBigtype(String.valueOf(((JSONObject) data1).get("itemCategory")));
                hxBasicGoodsParam.setGoodsBigtypedictId(0L);
                hxBasicGoodsParam.setGoodsXlbId(String.valueOf(data1.get("id")));

                list.add(hxBasicGoodsParam);
            };
        }
        if(list.size() > 0){
            hxBasicGoodsService.saveBatchList(list);
        }

        return ResponseData.success();
    }




    /**
     * 新增接口
     *
     * @author zhucx
     * @Date 2023-06-18
     */
    @RequestMapping("/addItem")
    @ResponseBody
    @Permission
    public ResponseData addItem(HxBasicGoodsParam hxBasicGoodsParam) {
    	User user = userService.getcurrentUser();
        Object goodsCustomerId = hxBasicGoodsParam.getGoodsCustomerId();
        if (goodsCustomerId != null) {
            BasicCustomer basicCustomer = basicCustomerService.getById(Integer.parseInt(goodsCustomerId.toString()));
            hxBasicGoodsParam.setGoodsCustomerName(basicCustomer.getCustomerName());
        }
        if(hxBasicGoodsParam!=null){
        	String goodsName = hxBasicGoodsParam.getGoodsName();
        	//解决参数中的 英文括号
        	if (goodsName!=null&&goodsName!="") {
        		goodsName = goodsName.replace("& #40;", "(");
        		goodsName = goodsName.replace("& #41;", ")");
        		hxBasicGoodsParam.setGoodsName(goodsName);
        	}
        }
        
        HxBasicGoodsParam param = new HxBasicGoodsParam();
        param.setGoodsCustomerId(hxBasicGoodsParam.getGoodsCustomerId());
        param.setGoodsNumber(hxBasicGoodsParam.getGoodsNumber());
        HxBasicGoodsResult result = hxBasicGoodsService.findBySpec(param,null);
        if(result != null) {
        	return ResponseData.error("商品编号已存在");
        }
        
    	hxBasicGoodsParam.setDeptId(user.getDeptId());
    	hxBasicGoodsParam.setDeliverId(user.getDeliverId());
    	hxBasicGoodsParam.setCreateName(user.getName());
        this.hxBasicGoodsService.add(hxBasicGoodsParam);
        return ResponseData.success();
    }

    /**
     * 编辑接口
     *
     * @author zhucx
     * @Date 2023-06-18
     */
    @RequestMapping("/editItem")
    @ResponseBody
    @Permission
    public ResponseData editItem(HxBasicGoodsParam hxBasicGoodsParam) {
    	User user = userService.getcurrentUser();
        Object goodsCustomerId = hxBasicGoodsParam.getGoodsCustomerId();
        if (goodsCustomerId != null) {
            BasicCustomer basicCustomer = basicCustomerService.getById(Integer.parseInt(goodsCustomerId.toString()));
            hxBasicGoodsParam.setGoodsCustomerName(basicCustomer.getCustomerName());
        }
        if(hxBasicGoodsParam!=null){
        	String goodsName = hxBasicGoodsParam.getGoodsName();
        	//解决参数中的 英文括号
        	if (goodsName!=null&&goodsName!="") {
        		goodsName = goodsName.replace("& #40;", "(");
        		goodsName = goodsName.replace("& #41;", ")");
        		hxBasicGoodsParam.setGoodsName(goodsName);
        	}
        }
        
        HxBasicGoodsParam param = new HxBasicGoodsParam();
        param.setId(hxBasicGoodsParam.getId());
        param.setGoodsCustomerId(hxBasicGoodsParam.getGoodsCustomerId());
        param.setGoodsNumber(hxBasicGoodsParam.getGoodsNumber());
        HxBasicGoodsResult result = hxBasicGoodsService.findBySpec(param,null);
        if(result != null) {
        	return ResponseData.error("商品编号已存在");
        }
        
    	hxBasicGoodsParam.setUpdateName(user.getName());
        this.hxBasicGoodsService.update(hxBasicGoodsParam);
        
        //更新绑定关系表
        hxBasicPositionGoodsService.lambdaUpdate()
        .eq(HxBasicPositionGoods::getGoodsId, hxBasicGoodsParam.getId())
        .set(HxBasicPositionGoods::getGoodsName, hxBasicGoodsParam.getGoodsName())
        .set(HxBasicPositionGoods::getGoodsNumber, hxBasicGoodsParam.getGoodsNumber())
        .set(HxBasicPositionGoods::getGoodsPcode69, hxBasicGoodsParam.getGoodsPcode69())
        .set(HxBasicPositionGoods::getGoodsSpecs, hxBasicGoodsParam.getGoodsSpecs())
        .set(HxBasicPositionGoods::getAnquanNum, hxBasicGoodsParam.getAnquanNum())
        .update();
        
        //更新待提交出库订单 体积、重量、金额
        HxOrderOutDetailedParam detailedParam = new HxOrderOutDetailedParam();
        detailedParam.setGoodsId(Long.parseLong(hxBasicGoodsParam.getId().toString()));
        List<HxOrderOutDetailedResult> odlist = hxOrderOutDetailedService.finddtjListBySpec(detailedParam);
		BigDecimal cgRate = new BigDecimal(hxBasicGoodsParam.getCgRate());
        for (HxOrderOutDetailedResult r : odlist) {
    		BigDecimal goodsVolume = new BigDecimal(hxBasicGoodsParam.getGoodsVolume());
    		BigDecimal goodsWeight = new BigDecimal(hxBasicGoodsParam.getGoodsWeight());
			BigDecimal goodsChargingPs = new BigDecimal(hxBasicGoodsParam.getGoodsChargingPs());
			BigDecimal ratiobig = new BigDecimal(r.getRate());
			BigDecimal goodsPrice = ratiobig.multiply(goodsChargingPs).setScale(3, BigDecimal.ROUND_HALF_DOWN);
			BigDecimal quantitybig = new BigDecimal(r.getPsNum());
			if(ratiobig.compareTo(cgRate) == -1) {
				//如果配送换算率 小于 采购换算率：  配送体积  =  采购体积/（采购换算率/配送换算率）
				BigDecimal div = cgRate.divide(ratiobig,3, BigDecimal.ROUND_HALF_DOWN);
				BigDecimal divv_v = goodsVolume.divide(div,4, BigDecimal.ROUND_HALF_DOWN);
				goodsVolume = divv_v;
				BigDecimal divv_w = goodsWeight.divide(div,3, BigDecimal.ROUND_HALF_DOWN);
				goodsWeight = divv_w;
			}
			if(ratiobig.compareTo(cgRate) == 1) {
				//如果配送换算率 大于 采购换算率：  配送体积  =  采购体积*（配送换算率/采购换算率）
				BigDecimal div = ratiobig.divide(cgRate,3, BigDecimal.ROUND_HALF_DOWN);
				BigDecimal divv_v = goodsVolume.multiply(div).setScale(4, BigDecimal.ROUND_HALF_DOWN);
				goodsVolume = divv_v;
				BigDecimal divv_w = goodsWeight.multiply(div).setScale(3, BigDecimal.ROUND_HALF_DOWN);
				goodsWeight = divv_w;
			}
	        HxOrderOutDetailedParam detailedParamupdate = new HxOrderOutDetailedParam();
	        detailedParamupdate.setId(r.getId());
	        detailedParamupdate.setGoodsWeight(goodsWeight.toString());
	        detailedParamupdate.setOutWeight(quantitybig.multiply(goodsWeight).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
	        detailedParamupdate.setGoodsVolume(goodsVolume.toString());
	        detailedParamupdate.setOutVolume(quantitybig.multiply(goodsVolume).setScale(4, BigDecimal.ROUND_HALF_DOWN).toString());
	        detailedParamupdate.setGoodsPrice(goodsPrice.toString());
	        detailedParamupdate.setOutMoney(quantitybig.multiply(goodsPrice).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
	        hxOrderOutDetailedService.update(detailedParamupdate);
		}
        
        //更新库存 体积、重量、金额
        HxStorageStockParam hxStorageStockParam = new HxStorageStockParam();
        hxStorageStockParam.setCustomerId(Long.parseLong(hxBasicGoodsParam.getGoodsCustomerId().toString()));
        hxStorageStockParam.setGoodsId(Long.parseLong(hxBasicGoodsParam.getId().toString()));
        List<HxStorageStockResult> slist = hxStorageStockService.findListBySpec(hxStorageStockParam);
        for (HxStorageStockResult sr : slist) {
    		BigDecimal goodsVolume = new BigDecimal(hxBasicGoodsParam.getGoodsVolume());
    		BigDecimal goodsWeight = new BigDecimal(hxBasicGoodsParam.getGoodsWeight());
			BigDecimal goodsChargingCg = new BigDecimal(hxBasicGoodsParam.getGoodsChargingCg());
			BigDecimal ratiobig = new BigDecimal(sr.getKcRate());
			BigDecimal goodsPrice = ratiobig.multiply(goodsChargingCg).setScale(3, BigDecimal.ROUND_HALF_DOWN);
			BigDecimal quantitybig = new BigDecimal(sr.getKcNum());
			if(ratiobig.compareTo(cgRate) == -1) {
				//如果配送换算率 小于 采购换算率：  配送体积  =  采购体积/（采购换算率/配送换算率）
				BigDecimal div = cgRate.divide(ratiobig,3, BigDecimal.ROUND_HALF_DOWN);
				BigDecimal divv_v = goodsVolume.divide(div,4, BigDecimal.ROUND_HALF_DOWN);
				goodsVolume = divv_v;
				BigDecimal divv_w = goodsWeight.divide(div,3, BigDecimal.ROUND_HALF_DOWN);
				goodsWeight = divv_w;
			}
			if(ratiobig.compareTo(cgRate) == 1) {
				//如果配送换算率 大于 采购换算率：  配送体积  =  采购体积*（配送换算率/采购换算率）
				BigDecimal div = ratiobig.divide(cgRate,3, BigDecimal.ROUND_HALF_DOWN);
				BigDecimal divv_v = goodsVolume.multiply(div).setScale(4, BigDecimal.ROUND_HALF_DOWN);
				goodsVolume = divv_v;
				BigDecimal divv_w = goodsWeight.multiply(div).setScale(3, BigDecimal.ROUND_HALF_DOWN);
				goodsWeight = divv_w;
			}
			HxStorageStockParam detailedParamupdate = new HxStorageStockParam();
	        detailedParamupdate.setId(sr.getId());
	        detailedParamupdate.setGoodsWeight(goodsWeight.toString());
	        detailedParamupdate.setStockWeight(quantitybig.multiply(goodsWeight).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
	        detailedParamupdate.setGoodsVolume(goodsVolume.toString());
	        detailedParamupdate.setStockVolume(quantitybig.multiply(goodsVolume).setScale(4, BigDecimal.ROUND_HALF_DOWN).toString());
	        detailedParamupdate.setGoodsPrice(goodsPrice.toString());
	        detailedParamupdate.setStockMoney(quantitybig.multiply(goodsPrice).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
	        hxStorageStockService.update(detailedParamupdate);
		}
        return ResponseData.success();
    }

    @Autowired
    private HxStorageStockService hxStorageStockService;

    @Autowired
    private HxOrderOutDetailedService hxOrderOutDetailedService;

    @Autowired
    private HxBasicPositionGoodsService hxBasicPositionGoodsService;

    /**
     * 删除接口
     *
     * @author zhucx
     * @Date 2023-06-18
     */
    @RequestMapping("/delete")
    @ResponseBody
    @Permission
    public ResponseData delete(HxBasicGoodsParam hxBasicGoodsParam) {
        this.hxBasicGoodsService.delete(hxBasicGoodsParam);
        return ResponseData.success();
    }

    /**
     * 查看详情接口
     *
     * @author zhucx
     * @Date 2023-06-18
     */
    @RequestMapping("/detail")
    @ResponseBody
    public ResponseData detail(HxBasicGoodsParam hxBasicGoodsParam) {
        HxBasicGoods detail = this.hxBasicGoodsService.getById(hxBasicGoodsParam.getId());
        return ResponseData.success(detail);
    }

    /**
     * 查询列表
     * @author zhucx
     * @Date 2023-06-18
     */
    @ResponseBody
    @RequestMapping("/list")
    public LayuiPageInfo list(HxBasicGoodsParam hxBasicGoodsParam,String condition ) {
    	User user = userService.getcurrentUser();
    	hxBasicGoodsParam.setDeptId(user.getDeptId());
        return this.hxBasicGoodsService.findPageBySpec(hxBasicGoodsParam,condition,user.getOperateId());
    }


    /**
     * 一品多位查询
     * @param hxBasicGoodsParam
     * @return
     */
    @ResponseBody
    @RequestMapping("/ypdwList")
    public LayuiPageInfo ypdwList(HxBasicGoodsParam hxBasicGoodsParam) {
        return this.hxBasicGoodsService.findYpdwPageBySpec(hxBasicGoodsParam);
    }
    /**
     * 需要维护商品69码
     * @param hxBasicGoodsParam
     * @return
     */
    @ResponseBody
    @RequestMapping("/WHList")
    public LayuiPageInfo WHList(HxBasicGoodsParam hxBasicGoodsParam) {
        return this.hxBasicGoodsService.findWHPageBySpec(hxBasicGoodsParam);
    }
    /**
     * 有库存，无绑定关系商品
     * @param hxBasicGoodsParam
     * @return
     */
    @ResponseBody
    @RequestMapping("/gjkcWgxList")
    public LayuiPageInfo gjkcWgxList(HxBasicGoodsParam hxBasicGoodsParam) {
        return this.hxBasicGoodsService.findGjkcWgxPageBySpec(hxBasicGoodsParam);
    }

    
    /**
     * 查询列表
     *
     * @author zhucx
     * @Date 2023-08-15
     */
    @ResponseBody
    @RequestMapping("/listAll")
    public List<HxBasicGoodsResult> listAll(HxBasicGoodsParam hxBasicGoodsParam,String condition ) {
    	User user = userService.getcurrentUser();
    	hxBasicGoodsParam.setDeptId(user.getDeptId());
        return this.hxBasicGoodsService.findlistAllBySpec(hxBasicGoodsParam,condition,user.getOperateId());
    }

    /**
     *
     * 判断库存
     */
    @ResponseBody
    @RequestMapping("kucun")
    public ResponseData kucun(HxStorageStockParam hxStorageStockParam){
       return this.hxBasicGoodsService.gcjy(hxStorageStockParam);
    }
    @ResponseBody
    @RequestMapping("/detailedGoodsId")
    public ResponseData detailedGoodsId(Integer  goodsId) {

        List<HxBasicGoods> list = hxBasicGoodsService.lambdaQuery()
                .select(HxBasicGoods::getJibenUnit, HxBasicGoods::getCgUnit, HxBasicGoods::getPsUnit, HxBasicGoods::getPfUnit, HxBasicGoods::getKcUnit)
                .eq(HxBasicGoods::getId, goodsId)
                .list();

        return ResponseData.success(list);
    }

    // 跳转到拉取商品分类页面
    @RequestMapping("/pickTcslProducts")
    public String pickTcslProducts(Model model) {
        User user = userService.getcurrentUser();
        Long deptId = user.getDeptId();
        Long deliverId = user.getDeliverId();
        //查询可选择客户
        model.addAttribute("customerlist", basicCustomerService.findAvailableList(user.getDeptId(),user.getDeliverId(),user.getOperateId()));

        //查询可选择仓库
        model.addAttribute("wlist", basicWarehouseService.findAvailableList(deptId,deliverId,user.getOperateId()));
        return PREFIX + "/pickTcslProducts.html";
    }

}


